package com.tianxiao.faas.biz.infrastructure.facade;

import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.tianxiao.faas.common.exception.biz.BizException;
import com.tianxiao.faas.common.util.UUIDUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;

@Component
public class ObjectStoreFacade {
    static final Logger logger = LoggerFactory.getLogger(ObjectStoreFacade.class);
    @Value("${spring.tengxun.bucketName}")
    private String bucketName;
    @Resource
    private COSClient cosClient;

    static final String CDN_HOST = "https://cdn.cornsee.com/";


    static final  String tempDir = System.getProperty("java.io.tmpdir");

    public String staticResourceUpload(InputStream in, String name) {
        if (in == null || name == null) {
            throw new BizException("上传异常，上传内容不能为空");
        }
        String suffixName = name.substring(name.lastIndexOf("."));

        String s = UUIDUtils.newUUID();
        String fileName = s + suffixName;
        String key = "static/" + fileName;
        File file = new File(tempDir, fileName);
        try {
            file.createNewFile();
            FileUtils.copyInputStreamToFile(in, file);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);

            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            logger.info("putObject,result:{}", JSON.toJSONString(putObjectResult));
            return CDN_HOST + putObjectRequest.getKey();
        } catch (Exception e) {
            logger.error("staticResourceUpload-error",e);
        }
        return null;
    }
}
